import java.util.Arrays;

//归并排序
public class mergeSort
{

    public static int[] mergeSort(int[] nums, int l, int r)
    {
        if (l == r)
            return new int[]{nums[l]};

        int mid = (l + r) / 2;
        int[] leftArr = mergeSort(nums, l, mid); //左有序数组
        int[] rightArr = mergeSort(nums, mid + 1, r); //右有序数组
        int[] newNum = new int[leftArr.length + rightArr.length]; //新有序数组

        int m = 0, i = 0, j = 0;
        while (i < leftArr.length && j < rightArr.length)
        {
            newNum[m++] = leftArr[i] < rightArr[j] ? leftArr[i++] : rightArr[j++];
        }
        while (i < leftArr.length)
            newNum[m++] = leftArr[i++];
        while (j < rightArr.length)
            newNum[m++] = rightArr[j++];
        return newNum;
    }

    public static void main(String[] args)
    {
        int[] arr = getRandomArray(20);
        for (int x : arr)
        {
            System.out.print(x + " ");
        }
        System.out.println();
        int[] newArr = mergeSort(arr, 0, arr.length - 1);
        for (int x : newArr)
        {
            System.out.print(x + " ");
        }
    }


    public static int[] getRandomArray(int n)
    {
        int[] arr = new int[10];
        for (int i = 0; i < 10; i++)
        {
            arr[i] = (int) (Math.random() * n + 1);
        }
        return arr;
    }
}
